package com.zhao.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.Util.plate.calendar.ProgrammerCalendar;
import com.zhao.pojo.Calendars;
import com.zhao.pojo.Dataup;
import com.zhao.service.CalendarService;
import com.zhao.service.DataupService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class JobConfig {

    @Autowired
    DataupService dataupService;
    @Autowired
    CalendarService calendarService;

    @Scheduled(cron = "0 0 0 * * ? ")
    private void dbBackup() throws Exception {
        String ip="localhost";
        //获取存储位置
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());

        String rootPath =System.getProperty("user.dir")+"/upload/Mysql/";

        // 新文件名
        String newFileName = "Mysql" + res +".sql";
        // 创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1));

        // 新文件
        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        String cmd = "cmd /c mysqldump -h"+ip+" -p3306 -uroot -px5 blogs>"+newFile.getPath();
        Process process = Runtime.getRuntime().exec(cmd);//执行语句
        process.waitFor();//等待上述命令执行完毕后打印下面log
        log.info("数据库备份结束，备份结果：{}",process.exitValue() == 0 ? "success" : "fail");
        //存储到数据库
        Dataup dataup = new Dataup();
        dataup.setSqlname(newFileName);
        dataup.setOperator("系统备份");
        dataup.setAbsolutepath(newFile.getPath());
        dataupService.save(dataup);
    }
    @Scheduled(cron = "0 20 5 * * ? ")
    private void programmerCalendar(){
        Calendars calendars = ProgrammerCalendar.generateCalendar();
        List<Calendars> title = calendarService.list(new QueryWrapper<Calendars>().eq("title", calendars.getTitle()));
        if (title.isEmpty()){
            calendarService.save(calendars);
        }
    }
}